<script setup>
import { ref, onMounted, computed, watch } from "vue";
import { VueFlow, useVueFlow, Panel, } from "@vue-flow/core";
import { Background } from "@vue-flow/background";
import { MiniMap } from "@vue-flow/minimap";
import { Controls } from "@vue-flow/controls";
import { useFlowStore } from "../stores/flowStore";
import { nodeTypes, nodeConfig } from "./NodeTypes";
// import EdgeAddButton from "./EdgeAddButton.vue";
import "@vue-flow/core/dist/style.css";
import "@vue-flow/core/dist/theme-default.css";
import "@vue-flow/controls/dist/style.css";
import "@vue-flow/minimap/dist/style.css";

// 自定义边类型
// const edgeTypes = {
//   'smoothstep': EdgeAddButton,
// };

// 初始化流程图存储
const flowStore = useFlowStore();

// 节点工具栏状态
const showNodeToolbar = ref(true);
const selectedNodeType = ref(null);

// 代码生成面板状态
const showCodePanel = ref(false);

// 初始化开始和结束节点的ID
const startNodeId = ref(null);
const endNodeId = ref(null);

// 使用VueFlow的钩子获取流程图实例
const {
  findNode,
  onConnect,
  onNodeDragStop,
  onPaneReady,
  project,
  vueFlowRef,
  onEdgesChange,
  getEdges,
  getNodes,
  addEdges,
} = useVueFlow();

// 监听节点和边的变化，更新选中的元素
watch(
  () => flowStore.selectedElements,
  (newElements) => {
    if (newElements && newElements.length > 0) {
      // 处理选中元素的逻辑
    }
  }
);

// 添加节点到流程图 - 已禁用直接添加功能
function addNode(type) {
  // 禁用直接添加节点功能
  alert('请在连线上添加节点');
  return;
}

// 处理节点连接
function handleConnect(connection) {
  if (connection.source && connection.target) {
    flowStore.addEdge({
      source: connection.source,
      target: connection.target,
      sourceHandle: connection.sourceHandle,
      targetHandle: connection.targetHandle,
      type: 'smoothstep',
    });
  }
}

// 处理节点拖动结束
function handleNodeDragStop(event, node) {
  flowStore.updateNode(node.id, { position: node.position });
}

// 处理节点删除
function handleNodeRemove(nodeId) {
  // 如果是开始或结束节点，则不允许删除
  if (nodeId === startNodeId.value) {
    alert('不能删除开始节点');
    return;
  }
  if (nodeId === endNodeId.value) {
    alert('不能删除结束节点');
    return;
  }
  
  flowStore.removeNode(nodeId);
}

// 处理边删除
function handleEdgeRemove(edgeId) {
  flowStore.removeEdge(edgeId);
}

// 生成代码
function generateCode() {
  flowStore.generateCode();
  showCodePanel.value = true;
}

// 清空流程图
function clearFlow() {
  if (confirm("确定要清空当前流程图吗？")) {
    flowStore.clearFlow();
  }
}

// 导出流程图数据
function exportFlow() {
  const flowData = flowStore.exportFlow();
  const dataStr = JSON.stringify(flowData, null, 2);
  const dataUri =
    "data:application/json;charset=utf-8," + encodeURIComponent(dataStr);

  const exportFileDefaultName = "flow-data.json";

  const linkElement = document.createElement("a");
  linkElement.setAttribute("href", dataUri);
  linkElement.setAttribute("download", exportFileDefaultName);
  linkElement.click();
}

// 导入流程图数据
function importFlow() {
  const input = document.createElement("input");
  input.type = "file";
  input.accept = ".json";

  input.onchange = (event) => {
    const file = event.target.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        try {
          const flowData = JSON.parse(e.target.result);
          flowStore.importFlow(flowData);
        } catch (error) {
          alert("导入失败：无效的流程图数据");
          console.error("导入失败：", error);
        }
      };
      reader.readAsText(file);
    }
  };

  input.click();
}

// 初始化连接事件
onConnect(handleConnect);

// 初始化节点拖动事件
onNodeDragStop(handleNodeDragStop);

// 流程图就绪事件
onPaneReady(() => {
  console.log("流程图编辑器已就绪");
  
  // 初始化流程图，添加开始和结束节点
  initializeFlow();
});

// 初始化流程图
function initializeFlow() {
  // 如果流程图为空，则添加开始和结束节点
  if (flowStore.nodes.length === 0) {
    // 添加开始节点
    const startNode = flowStore.addNode({
      type: 'start',
      position: { x: window.innerWidth / 2 - 100, y: window.innerHeight / 2 - 100 },
      data: {},
    });
    startNodeId.value = startNode.id;
    
    // 添加结束节点
    const endNode = flowStore.addNode({
      type: 'end',
      position: { x: window.innerWidth / 2 - 100, y: window.innerHeight / 2 + 100 },
      data: {},
    });
    endNodeId.value = endNode.id;
    
    // 添加连接线
    flowStore.addEdge({
      source: startNode.id,
      target: endNode.id,
      sourceHandle: 'source',
      targetHandle: 'target',
      type: 'smoothstep',
    });
  } else {
    // 如果已有节点，找出开始和结束节点
    const nodes = flowStore.nodes;
    for (const node of nodes) {
      if (node.type === 'start') {
        startNodeId.value = node.id;
      } else if (node.type === 'end') {
        endNodeId.value = node.id;
      }
    }
  }
}

// 处理在边上添加节点
function handleEdgeAddNode(data) {
  const { edgeId, nodeType, position } = data;
  
  // 获取要添加节点的边
  const edge = flowStore.edges.find(e => e.id === edgeId);
  if (!edge) return;
  
  // 创建新节点
  const newNode = flowStore.addNode({
    type: nodeType,
    position,
    data: nodeType === 'initiator' ? { initiator: '发起人' } : 
          nodeType === 'approver' ? { approver: '审批人' } : {},
  });
  
  // 删除原来的边
  flowStore.removeEdge(edgeId);
  
  // 添加从源节点到新节点的边
  flowStore.addEdge({
    source: edge.source,
    target: newNode.id,
    sourceHandle: edge.sourceHandle,
    targetHandle: 'target',
    type: 'smoothstep',
  });
  
  // 添加从新节点到目标节点的边
  let sourceHandle = 'source';
  
  // 根据节点类型选择合适的输出端口
  if (nodeType === 'condition') {
    sourceHandle = 'source-true';
  } else if (nodeType === 'loop') {
    sourceHandle = 'source-body';
  }
  
  flowStore.addEdge({
    source: newNode.id,
    target: edge.target,
    sourceHandle: sourceHandle,
    targetHandle: edge.targetHandle,
    type: 'smoothstep',
  });
}

// 处理边更新
function handleEdgeUpdate(params) {
  // 更新边的连接
  const { edge, connection } = params;
  flowStore.removeEdge(edge.id);
  flowStore.addEdge({
    ...connection,
    type: 'smoothstep',
  });
}

// 复制代码到剪贴板
function copyToClipboard() {
  navigator.clipboard.writeText(flowStore.generatedCode)
    .then(() => {
      alert('代码已复制到剪贴板');
    })
    .catch(err => {
      console.error('复制失败:', err);
      alert('复制失败，请手动复制');
    });
}
</script>

<template>
  <div class="flow-editor">
    <!-- VueFlow 流程图组件 -->
    <VueFlow
      v-model="flowStore.nodes"
      v-model:edges="flowStore.edges"
      :node-types="nodeTypes"
      :edge-types="edgeTypes"
      :default-viewport="{ x: 0, y: 0, zoom: 1 }"
      class="flow-viewport"
      @nodeClick="(e, node) => flowStore.selectElements([node])"
      @paneClick="() => flowStore.selectElements([])"
      @edge-update="handleEdgeUpdate"
    >      <!-- 自定义边组件 -->
      <template #edge-smoothstep="edgeProps">
        <EdgeAddButton v-bind="edgeProps" @add="handleEdgeAddNode" />
      </template>
      <!-- 背景网格 -->
      <Background pattern-color="#aaa" gap="20" />

      <!-- 控制面板 -->
      <Controls />

      <!-- 小地图 -->
      <MiniMap />

      <!-- 顶部工具栏 -->
      <Panel position="top-center" class="top-toolbar">
        <div class="toolbar-container">
          <button
            @click="showNodeToolbar = !showNodeToolbar"
            class="toolbar-btn"
          >
            {{ showNodeToolbar ? "隐藏节点工具栏" : "显示节点工具栏" }}
          </button>
          <button @click="generateCode" class="toolbar-btn generate-btn">
            生成代码
          </button>
          <button
            @click="flowStore.undo"
            :disabled="!flowStore.canUndo"
            class="toolbar-btn"
          >
            撤销
          </button>
          <button
            @click="flowStore.redo"
            :disabled="!flowStore.canRedo"
            class="toolbar-btn"
          >
            重做
          </button>
          <button @click="clearFlow" class="toolbar-btn danger-btn">
            清空
          </button>
          <button @click="exportFlow" class="toolbar-btn">导出</button>
          <button @click="importFlow" class="toolbar-btn">导入</button>
        </div>
      </Panel>

      <!-- 节点工具栏 -->
      <Panel v-if="showNodeToolbar" position="top-left" class="node-toolbar">
        <div class="node-toolbar-container">
          <h3>节点类型</h3>
          <div class="node-type-list">
            <div
              v-for="node in nodeConfig"
              :key="node.type"
              class="node-type-item"
              :style="{ borderColor: node.color }"
              @click="addNode(node.type)"
            >
              <div
                class="node-type-color"
                :style="{ backgroundColor: node.color }"
              ></div>
              <div class="node-type-info">
                <div class="node-type-label">{{ node.label }}</div>
                <div class="node-type-desc">{{ node.description }}</div>
              </div>
            </div>
          </div>
        </div>
      </Panel>

      <!-- 代码生成面板 -->
      <Panel v-if="showCodePanel" position="bottom-right" class="code-panel">
        <div class="code-panel-container">
          <div class="code-panel-header">
            <h3>生成的JavaScript代码</h3>
            <button @click="showCodePanel = false" class="close-btn">×</button>
          </div>
          <pre class="code-display">{{ flowStore.generatedCode }}</pre>
          <button @click="copyToClipboard" class="toolbar-btn">复制代码</button>
        </div>
      </Panel>
    </VueFlow>
  </div>
</template>

<style scoped>
.flow-editor {
  width: 100%;
  height: 100vh;
  position: relative;
}

.flow-viewport {
  width: 100%;
  height: 100%;
  background-color: #f5f5f5;
}

/* 工具栏样式 */
.toolbar-container {
  display: flex;
  gap: 10px;
  padding: 10px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.toolbar-btn {
  padding: 8px 12px;
  border-radius: 4px;
  border: 1px solid #ddd;
  background-color: white;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.toolbar-btn:hover {
  background-color: #f0f0f0;
}

.toolbar-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.generate-btn {
  background-color: #4caf50;
  color: white;
  border: none;
}

.generate-btn:hover {
  background-color: #388e3c;
}

.danger-btn {
  background-color: #f44336;
  color: white;
  border: none;
}

.danger-btn:hover {
  background-color: #d32f2f;
}

/* 节点工具栏样式 */
.node-toolbar-container {
  width: 250px;
  padding: 15px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.node-toolbar-container h3 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 16px;
  color: #333;
}

.node-type-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.node-type-item {
  display: flex;
  align-items: center;
  padding: 8px;
  border-radius: 4px;
  border: 1px solid #ddd;
  cursor: pointer;
  transition: all 0.2s;
}

.node-type-item:hover {
  background-color: #f5f5f5;
  transform: translateY(-2px);
}

.node-type-color {
  width: 20px;
  height: 20px;
  border-radius: 4px;
  margin-right: 10px;
}

.node-type-info {
  flex: 1;
}

.node-type-label {
  font-weight: bold;
  font-size: 14px;
  margin-bottom: 2px;
}

.node-type-desc {
  font-size: 12px;
  color: #666;
}

/* 代码面板样式 */
.code-panel-container {
  width: 400px;
  max-height: 400px;
  padding: 15px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.code-panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.code-panel-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #666;
}

.close-btn:hover {
  color: #f44336;
}

.code-display {
  flex: 1;
  overflow: auto;
  background-color: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  font-family: monospace;
  font-size: 14px;
  margin-bottom: 10px;
  white-space: pre-wrap;
}
</style>